<?php

namespace App\Models\Payment\Repositories;

use App\Models\Payment\Payment;
use App\Models\Payment\PaymentLogs;
use App\Models\Payment\Repositories\Interfaces\PaymentLogsRepositoryInterface;
use App\Trip\Repository\BaseRepository;
use Illuminate\Support\Facades\Cache;

class PaymentLogsRepository extends BaseRepository implements PaymentLogsRepositoryInterface
{
    public function __construct(PaymentLogs $model)
    {
        parent::__construct($model);
    }

    public function saveLog(Payment $payment): PaymentLogs
    {
        if ($log = $this->findOneByPayment($payment)) {
            return $log;
        }

        return $this->create([
            "mchid"       => $payment->mchid,
            "secret_key"  => $payment->secret_key,
            "secret_key2" => $payment->secret_key2,
        ]);
    }

    public function findOneByPayment(Payment $payment): ?PaymentLogs
    {
        return $this->findOneByMchId($payment->getMchId());
    }

    public function findOneByMchId(string $mchid): ?PaymentLogs
    {
        $cache_key = "PaymentLog:{$mchid}";
        if (Cache::has($cache_key)) {
            return Cache::get($cache_key);
        }

        $log = $this->findOneBy(['mchid' => $mchid]);
        if ($log) {
            Cache::forever($cache_key, $log);
        }
        return $log;
    }
}